<template>
  <div class="edit-lesson-plan">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-button :icon="ArrowLeft" circle @click="handleCancel" />
          <h1 class="page-title">{{ isEdit ? '编辑教案' : '创建新教案' }}</h1>
        </div>
        <div class="header-actions">
          <el-space>
            <el-button size="large" @click="handleCancel">取消</el-button>
            <el-button type="primary" size="large" @click="handleSaveDraft" :loading="saving">
              <el-icon><DocumentCopy /></el-icon>
              保存草稿
            </el-button>
            <el-button type="success" size="large" @click="handlePublish" :loading="publishing">
              <el-icon><Promotion /></el-icon>
              发布教案
            </el-button>
          </el-space>
        </div>
      </div>
    </div>
      
    <!-- 主内容区域 -->
    <div class="main-content">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        class="lesson-form"
        size="large"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h2 class="section-title">
            <el-icon><Document /></el-icon>
            基本信息
          </h2>
          
          <el-form-item label="教案标题" prop="title">
            <el-input
              v-model="form.title"
              placeholder="请输入一个清晰明确的教案标题"
              maxlength="100"
              show-word-limit
              clearable
            >
              <template #prefix>
                <el-icon><EditPen /></el-icon>
              </template>
            </el-input>
          </el-form-item>
            
          <el-row :gutter="24">
            <el-col :xs="24" :sm="24" :md="8">
              <el-form-item label="学科分类" prop="subject">
                <el-select
                  v-model="form.subject"
                  placeholder="请选择学科"
                  style="width: 100%"
                  clearable
                  filterable
                >
                  <template #prefix>
                    <el-icon><Reading /></el-icon>
                  </template>
                  <el-option
                    v-for="subject in subjectOptions"
                    :key="subject._id"
                    :label="subject.name"
                    :value="subject.name"
                  >
                    <span style="float: left">{{ subject.name }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ (subject as any).lessonPlanCount || 0 }} 个教案
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :sm="24" :md="8">
              <el-form-item label="适用年级" prop="grade">
                <el-select
                  v-model="form.grade"
                  placeholder="请选择年级"
                  style="width: 100%"
                  clearable
                  filterable
                >
                  <template #prefix>
                    <el-icon><School /></el-icon>
                  </template>
                  <el-option
                    v-for="grade in gradeOptions"
                    :key="grade._id"
                    :label="grade.name"
                    :value="grade.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :sm="24" :md="8">
              <el-form-item label="课程类型" prop="courseType">
                <el-select
                  v-model="form.courseType"
                  placeholder="请选择课程类型"
                  style="width: 100%"
                  clearable
                  filterable
                >
                  <template #prefix>
                    <el-icon><Collection /></el-icon>
                  </template>
                  <el-option
                    v-for="courseType in courseTypeOptions"
                    :key="courseType._id"
                    :label="courseType.name"
                    :value="courseType.name"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
            
          <el-row :gutter="24">
            <el-col :xs="24" :sm="24" :md="16">
              <el-form-item label="标签关键词">
                <el-select
                  v-model="form.tags"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择或输入标签，有助于其他教师发现您的教案"
                  style="width: 100%"
                  multiple-limit="10"
                >
                  <template #prefix>
                    <el-icon><PriceTag /></el-icon>
                  </template>
                  <el-option
                    v-for="tag in tagOptions"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  >
                    <el-tag>{{ tag }}</el-tag>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :sm="24" :md="8">
              <el-form-item label="公开设置">
                <el-space>
                  <el-switch
                    v-model="form.isPublic"
                    active-text="公开"
                    inactive-text="私有"
                    inline-prompt
                    style="--el-switch-on-color: #67c23a"
                  />
                  <el-tooltip
                    content="公开的教案其他用户可以查看和学习"
                    placement="top"
                  >
                    <el-icon class="info-icon"><InfoFilled /></el-icon>
                  </el-tooltip>
                </el-space>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
          
        <!-- 教案内容 -->
        <div class="form-section">
          <h2 class="section-title">
            <el-icon><EditPen /></el-icon>
            教案内容
          </h2>
          
          <el-form-item prop="content">
            <div class="editor-wrapper">
              <!-- 富文本编辑器工具栏 -->
              <Toolbar
                class="editor-toolbar"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                mode="default"
              />
              <!-- 富文本编辑器 -->
              <Editor
                class="editor-content"
                v-model="form.content"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </div>
          
        <!-- 附件上传 -->
        <div class="form-section">
          <h2 class="section-title">
            <el-icon><Folder /></el-icon>
            附件文件
          </h2>
          
          <FileUpload
            ref="fileUploadRef"
            file-type="document"
            :multiple="true"
            :limit="10"
            :max-size="10"
            :initial-files="fileList"
            @success="handleUploadSuccess"
            @error="handleUploadError"
            @remove="handleRemove"
            @change="handleFileListChange"
          />
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, shallowRef, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
import {
  InfoFilled,
  UploadFilled,
  ArrowLeft,
  DocumentCopy,
  Promotion,
  Document,
  EditPen,
  Reading,
  School,
  Collection,
  PriceTag,
  Folder
} from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
import { useAuthStore } from '@/stores/auth'
import { lessonPlanApi, type LessonPlan, type CreateLessonPlanData, type UpdateLessonPlanData } from '@/api/lessonPlan'
import { categoryApi, type Category } from '@/api/category'
import { fileApi } from '@/api/file'
import FileUpload from '@/components/FileUpload.vue'

// 富文本编辑器配置
const editorRef = shallowRef<IDomEditor>()
const editorConfig: Partial<IEditorConfig> = {
  placeholder: '请输入教案内容...',
  autoFocus: false,
  MENU_CONF: {
    uploadImage: {
      server: '/api/files/upload',
      fieldName: 'file',
      maxFileSize: 5 * 1024 * 1024, // 5MB
      allowedFileTypes: ['image/*'],
      headers: {
        Authorization: `Bearer ${useAuthStore().token}`
      },
      customInsert(res: any, insertFn: any) {
        if (res.success && res.data) {
          const url = res.data.url
          const alt = res.data.filename || '图片'
          insertFn(url, alt, url)
        }
      }
    }
  }
}

const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    'headerSelect',
    'bold',
    'italic',
    'underline',
    'through',
    '|',
    'bulletedList',
    'numberedList',
    'todo',
    '|',
    'blockquote',
    'codeBlock',
    'insertLink',
    'insertImage',
    'insertTable',
    '|',
    'fontSize',
    'fontFamily',
    'lineHeight',
    'color',
    'bgColor',
    '|',
    'justifyLeft',
    'justifyCenter',
    'justifyRight',
    '|',
    'undo',
    'redo',
    'clearStyle'
  ]
}

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const formRef = ref<FormInstance>()
const fileUploadRef = ref<InstanceType<typeof FileUpload>>()

// 是否编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const form = reactive<CreateLessonPlanData & { _id?: string }>({
  title: '',
  content: '',
  subject: '',
  grade: '',
  courseType: '',
  tags: [],
  isPublic: true,
  status: 'draft'
})

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入教案标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  courseType: [
    { required: true, message: '请选择课程类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入教案内容', trigger: 'blur' },
    { min: 50, message: '教案内容至少 50 个字符', trigger: 'blur' }
  ]
})

// 分类选项
const subjectOptions = ref<Category[]>([])
const gradeOptions = ref<Category[]>([])
const courseTypeOptions = ref<Category[]>([])
const tagOptions = ref<string[]>(['教学设计', '课件', '教学反思', '作业设计', '评价方案'])

// 文件上传
const fileList = ref<UploadFile[]>([])

// 其他状态
const saving = ref(false)
const publishing = ref(false)

// 富文本编辑器创建
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
  
  // 如果是编辑模式且内容已加载，设置编辑器内容
  if (isEdit.value && form.content) {
    editor.setHtml(form.content)
  }
}

// 加载分类选项
const loadCategories = async () => {
  try {
    const { data } = await categoryApi.getAll()
    if (data && data.grouped) {
      subjectOptions.value = data.grouped.subject || []
      gradeOptions.value = data.grouped.grade || []
      courseTypeOptions.value = data.grouped.courseType || []
    }
  } catch (error: any) {
    console.error('加载分类失败:', error)
  }
}

// 加载教案详情（编辑模式）
const loadLessonPlan = async () => {
  if (!isEdit.value) return
  
  try {
    const id = route.params.id as string
    const { data } = await lessonPlanApi.getById(id)
    
    // 填充表单数据
    Object.assign(form, {
      _id: data._id,
      title: data.title,
      content: data.content,
      subject: data.subject,
      grade: data.grade,
      courseType: data.courseType,
      tags: data.tags || [],
      isPublic: data.isPublic,
      status: data.status
    })
    
    // 如果编辑器已经创建，直接设置内容
    if (editorRef.value && data.content) {
      await nextTick()
      editorRef.value.setHtml(data.content)
    }
    
    // 处理已有附件
    if (data.attachments && data.attachments.length > 0) {
      fileList.value = data.attachments.map((url, index) => ({
        name: getFileName(url),
        url,
        uid: index,
        status: 'success'
      }))
    }
  } catch (error: any) {
    ElMessage.error(error.message || '加载教案失败')
    router.push('/lesson-plans')
  }
}

// 获取文件名
const getFileName = (path: string) => {
  return path.split('/').pop() || path
}

// 文件上传成功
const handleUploadSuccess = (file: UploadFile, response: any) => {
  console.log('文件上传成功:', file, response)
  ElMessage.success('文件上传成功')
}

// 文件上传失败
const handleUploadError = (error: Error, file: UploadFile) => {
  console.error('文件上传失败:', error, file)
  ElMessage.error('文件上传失败: ' + error.message)
}

// 移除文件
const handleRemove = async (file: UploadFile) => {
  try {
    // 如果文件有ID，调用后端API删除
    if (file.response?.data?.id) {
      await fileApi.delete(file.response.data.id)
      console.log('文件删除成功:', file.response.data.id)
    }
    return true
  } catch (error) {
    console.error('删除文件失败:', error)
    ElMessage.error('删除文件失败')
    return false
  }
}

// 文件列表变化
const handleFileListChange = (newFileList: UploadFile[]) => {
  fileList.value = newFileList
}

// 获取附件URL列表
const getAttachmentUrls = () => {
  return fileUploadRef.value?.getUrls() || []
}

// 保存草稿
const handleSaveDraft = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    const attachments = getAttachmentUrls()
    
    if (isEdit.value) {
      // 更新教案
      const { _id, ...formData } = form
      const updateData: UpdateLessonPlanData = {
        ...formData,
        status: 'draft',
        attachments
      }
      await lessonPlanApi.updateDraft(form._id!, updateData)
      ElMessage.success('草稿保存成功')
    } else {
      // 创建草稿
      const { _id, ...formData } = form
      const createData: CreateLessonPlanData = {
        ...formData,
        status: 'draft',
        attachments
      }
      const { data } = await lessonPlanApi.saveDraft(createData)
      ElMessage.success('草稿保存成功')
      // 跳转到编辑页面
      router.replace(`/lesson-plans/${data._id}/edit`)
    }
  } catch (error: any) {
    if (error !== false) {
      ElMessage.error(error.message || '保存失败')
    }
  } finally {
    saving.value = false
  }
}

// 发布教案
const handlePublish = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    await ElMessageBox.confirm(
      '发布后的教案将对其他用户可见，确定要发布吗？',
      '发布确认',
      {
        confirmButtonText: '确定发布',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    publishing.value = true
    const attachments = getAttachmentUrls()
    
    if (isEdit.value) {
      // 更新并发布
      const { _id, ...formData } = form
      const updateData: UpdateLessonPlanData = {
        ...formData,
        status: 'published',
        attachments
      }
      await lessonPlanApi.update(form._id!, updateData)
      if (form.status === 'draft') {
        await lessonPlanApi.publish(form._id!)
      }
    } else {
      // 创建并发布
      const { _id, ...formData } = form
      const createData: CreateLessonPlanData = {
        ...formData,
        status: 'published',
        attachments
      }
      const { data } = await lessonPlanApi.create(createData)
      form._id = data._id
    }
    
    ElMessage.success('发布成功')
    router.push(`/lesson-plans/${form._id}`)
  } catch (error: any) {
    if (error !== 'cancel' && error !== false) {
      ElMessage.error(error.message || '发布失败')
    }
  } finally {
    publishing.value = false
  }
}

// 取消编辑
const handleCancel = () => {
  ElMessageBox.confirm(
    '确定要取消编辑吗？未保存的内容将会丢失。',
    '取消确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '继续编辑',
      type: 'warning'
    }
  ).then(() => {
    router.back()
  }).catch(() => {
    // 用户选择继续编辑
  })
}

// 页面加载时初始化
onMounted(async () => {
  loadCategories()
  if (isEdit.value) {
    // 先加载数据，再等待DOM更新
    await loadLessonPlan()
  }
})

// 组件销毁时，销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style scoped>
.edit-lesson-plan {
  min-height: 100vh;
  background-color: #f0f2f5;
}

/* 页面头部 */
.page-header {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 主内容区域 */
.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 32px 24px;
}

.lesson-form {
  width: 100%;
}

/* 表单分区 */
.form-section {
  background: white;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.section-title {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title .el-icon {
  font-size: 24px;
  color: #409eff;
}

/* 表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 28px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  font-size: 15px;
  color: #303133;
  margin-bottom: 8px;
}

:deep(.el-input__wrapper),
:deep(.el-select) {
  border-radius: 8px;
}

:deep(.el-input__wrapper) {
  padding: 12px 16px;
}

:deep(.el-select .el-input__wrapper) {
  padding: 8px 16px;
}

:deep(.el-input__prefix) {
  margin-right: 8px;
  font-size: 18px;
  color: #909399;
}

/* 下拉框优化 */
:deep(.el-select-dropdown__item) {
  padding: 12px 20px;
  font-size: 14px;
}

:deep(.el-select-dropdown__item.selected) {
  font-weight: 600;
}

/* 标签选择器 */
:deep(.el-select__tags) {
  max-height: 80px;
  overflow-y: auto;
}

/* 信息图标 */
.info-icon {
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.info-icon:hover {
  color: #409eff;
}

/* 富文本编辑器 */
.editor-wrapper {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  overflow: hidden;
  background: white;
}

.editor-toolbar {
  border-bottom: 1px solid #e4e7ed;
}

.editor-content {
  height: 500px;
  overflow-y: auto;
}

:deep(.w-e-toolbar) {
  background-color: #f5f7fa !important;
  border: none !important;
  padding: 10px 15px !important;
}

:deep(.w-e-text-container) {
  background-color: white;
  border: none !important;
}

:deep(.w-e-text-container [data-slate-editor]) {
  padding: 20px !important;
  min-height: 460px !important;
}

:deep(.w-e-text) {
  line-height: 1.8;
}

/* 修复工具栏按钮样式 */
:deep(.w-e-bar-item) {
  margin: 0 2px !important;
}

:deep(.w-e-bar-item button) {
  border-radius: 4px !important;
  padding: 4px 8px !important;
}

:deep(.w-e-bar-item button:hover) {
  background-color: #e4e7ed !important;
}

:deep(.w-e-bar-divider) {
  margin: 0 8px !important;
  background-color: #dcdfe6 !important;
}


/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .header-left {
    width: 100%;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .main-content {
    padding: 16px;
  }
  
  .form-section {
    padding: 20px;
  }
  
  .section-title {
    font-size: 18px;
  }
  
  :deep(.w-e-text-container) {
    min-height: 300px;
  }
}
</style>